<template>
  <div>
    <form ref="form" enctype="multipart/form-data">
      <input id="file" type="file" name="file">
    </form>
    <form method="POST" action="http://127.0.0.1:8200/api/resource/upload" enctype="multipart/form-data">

      <input id="file" type="file" name="file">
      <input type="submit" value="提交">
    </form>
    <el-button @click="sendRequest">button</el-button>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  data() {
    return {
      signature: null
    }
  },
  mounted() {
    const form = this.$refs.form
    form.children[0].addEventListener('change', (e) => {
      console.log(this.signature)
      if (this.signature && Number(this.signature.expire) > Date.now / 1000) {
        this.send(this.signature, form.children[0].files[0], form)
      } else {
        request({
          url: '/service/oss/api/policy',
          method: 'get'
        }).then(result => {
          const data = result.data
          this.signature = data
          console.log(result)
          this.send(data, form.children[0].files[0], form)
        })
      }
    })
  },
  methods: {
    send(data, file, form) {
      const xhr = new XMLHttpRequest()
      xhr.open('POST', data.host)
      // xhr.open('POST', 'http://127.0.0.1:8200/api/resource/upload')
      const formData = new FormData(form)

      formData.append('name', file.name)
      // key表示上传到Bucket内的Object的完整路径，例如exampledir/exampleobject.txtObject，完整路径中不能包含Bucket名称。
      formData.append('key', `${data.dir}${file.name}`)
      formData.append('policy', data.policy)
      formData.append('OSSaccessKeyId', data.accessid)
      // 设置服务端返回状态码为200，不设置则默认返回状态码204。
      formData.append('success_action_status', '200')
      formData.append('callback', data.callback)
      formData.append('signature', data.signature)
      formData.delete('file')// 删除第一个file，保持file在最后
      formData.append('file', file)
      // 回调设置

      // xhr.setRequestHeader('x-oss-callback', data.callback)

      xhr.send(formData)
    },
    sendRequest() {
      const form = this.$refs.form
      form.children[0].click()
    }
  }
}
</script>

<style>

</style>
